package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * @author sunhl
 * @Description: 1-67-1 商品服务-API-品牌管理-统一异常处理
 *         @RestControllerAdvice 就是 @ResponseBody + @ControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
 * @Date: created in 2020/10/17 13:11
 * @Modified By:
 */
@Slf4j
@RestControllerAdvice
public class GulimallExceptionControllerAdvice {

    /**
     * 数据校验的异常处理
     * @param e org.springframework.web.bind.MethodArgumentNotValidException
     * @return com.atguigu.common.utils.R
     */
    @ExceptionHandler(value= MethodArgumentNotValidException.class)
    public R handleVaildException (MethodArgumentNotValidException e) {
        log.error("数据校验出现问题{}，异常类型：{}", e.getMessage(), e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        HashMap<String, String> errorMap = new HashMap<>(10);
        bindingResult.getFieldErrors().forEach(fieldError -> {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(), BizCodeEnume.VAILD_EXCEPTION.getMsg())
                .put("data", errorMap);
    }

    /**
     * 全局的异常处理
     * @param throwable java.lang.Throwable
     * @return com.atguigu.common.utils.R
     */
    @ExceptionHandler(value = Throwable.class)
    public R handleException (Throwable throwable) {
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(), BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }
}
